package com.kaizzi.data.ppt.template;

import com.fasterxml.jackson.databind.JsonNode;
import com.kaizzi.data.common.been.NameDouble;
import com.kaizzi.data.common.been.SeriesData;
import com.kaizzi.data.common.utils.StringUtil;
import com.kaizzi.data.jdl.service.LogService;
import com.kaizzi.data.ppt.TemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.sl.usermodel.TableCell;
import org.apache.poi.sl.usermodel.TableShape;
import org.apache.poi.xslf.usermodel.XSLFChart;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Kzen
 * @Description description
 * @date 2020/9/27
 */
@Component
@Slf4j
public class Template8 {

    @Resource
    private TemplateUtil templateUtil;
    @Resource
    private LogService logService;

    public void text(List<XSLFTextParagraph> textParagraphs,JsonNode data) {
        if(textParagraphs==null||textParagraphs.size()==0){
            return;
        }
        for (XSLFTextParagraph textParagraph : textParagraphs) {
            if(textParagraph==null){
                continue;
            }
            List<XSLFTextRun> textRuns = textParagraph.getTextRuns();
            if(textRuns==null){
                continue;
            }
            for (XSLFTextRun textRun : textRuns) {
                if (textRun == null || textRun.getXmlObject()  == null){
                    return;
                }
                try {
                    if (textRun.getRawText().equals("9KEY-2")){
                        String title = data.get("title").asText();
                        templateUtil.text(textParagraph,title,false);
                        break;
                    }
                    if (textRun.getRawText().equals("9KEY-1")){
                        String dataPeriod = data.get("dataPeriod").asText();
                        textRun.setText(dataPeriod);
                        break;
                    }
                }catch (Exception e){
                    logService.setDataLogStatus("ppt-error");
                    log.error("页码:{},异常原因:{}",8,e);
                }
            }
        }
    }

    //箭头
    public void simpleShape(int red, XSLFShape shape, JsonNode data) {
        if (red %10 !=0 || red ==0){
            return;
        }
        String jsonKey = "page8s";
        String jsonKey1 ;
        switch (red){
            case 10:
                jsonKey = "userChannelSources";
                jsonKey1 = "appletCount";
                break;
            case 20:
                jsonKey = "userChannelSources";
                jsonKey1 = "king";
                break;
            case 30:
                jsonKey1 = "otherApp";
                break;
            case 40:
                jsonKey1 = "conversation";
                break;
            case 50:
                jsonKey1 = "taskUsed";
                break;
            case 60:
                jsonKey1 = "search";
                break;
            case 70:
                jsonKey1 = "taskMyApp";
                break;
            case 80:
                jsonKey1 = "pubMenu";
                break;
            case 90:
                jsonKey1 = "pubArticle";
                break;
            case 100:
                jsonKey1 = "qrCode";
                break;
            case 110:
                jsonKey1 = "scanning";
                break;
            case 120:
                jsonKey = "userNatureSources";
                jsonKey1 = "utcCount";
                break;
            case 130:
                jsonKey = "userNatureSources";
                jsonKey1 = "naturalCount";
                break;
            case 140:
                jsonKey = "userNatureSources";
                jsonKey1 = "wesCount";
                break;
            case 150:
                jsonKey = "userChannelSources";
                jsonKey1 = "teamCount";
                break;
            default:
                jsonKey1 = "";
                break;
        }
        int trend = getSimpleData(data,jsonKey,jsonKey1);
        templateUtil.replaceSimpleShape(trend,shape);
    }

    private int getSimpleData(JsonNode data, String jsonKey, String jsonKey1) {
        int trend = data.get(jsonKey).get(1).get(jsonKey1).get("trend").asInt();
        if (trend == 0){
            return 1;
        }
        return trend;
    }

    //柱图
    public void barChart(CTPlotArea plot, JsonNode data, XSSFWorkbook workbook, XSSFSheet sheet, XSLFChart chart) {
        String value = plot.getBarChartList().get(0).getSerList().get(0).getCat().getStrRef().getStrCache().getPtArray(0).getV();
        //获取柱形图数据1
        List<SeriesData> seriesDatas ;
        if (value.equals("自然流量（其他）")){
            seriesDatas = getBarData1(data);
        }else {
            seriesDatas = getBarData2(data);
        }
        log.info("bar chart:{}",seriesDatas);
        templateUtil.barChart(plot,seriesDatas,workbook,sheet,chart);
    }

    private List<SeriesData> getBarData2(JsonNode data) {
        JsonNode jsonNode = data.get("page8s");
        List<SeriesData> seriesDatas = new ArrayList<>();

        for (JsonNode dateJson:jsonNode) {
            List<NameDouble> tempDatas = new ArrayList<>();
            String date = dateJson.get("date").get("value").asText();

            NameDouble data1 = new NameDouble("其他小程序",StringUtil.doubleFormat(dateJson.get("otherApp").get("value").asText()));
            NameDouble data2 = new NameDouble("会话",StringUtil.doubleFormat(dateJson.get("conversation").get("value").asText()));
            NameDouble data3 = new NameDouble("任务栏最近使用",StringUtil.doubleFormat(dateJson.get("taskUsed").get("value").asText()));
            NameDouble data4 = new NameDouble("搜索",StringUtil.doubleFormat(dateJson.get("search").get("value").asText()));
            NameDouble data5 = new NameDouble("任务栏我的小程序",StringUtil.doubleFormat(dateJson.get("taskMyApp").get("value").asText()));
            NameDouble data6 = new NameDouble("公众号菜单栏",StringUtil.doubleFormat(dateJson.get("pubMenu").get("value").asText()));
            NameDouble data7 = new NameDouble("公众号文章",StringUtil.doubleFormat(dateJson.get("pubArticle").get("value").asText()));
            NameDouble data8 = new NameDouble("长按识别二维码",StringUtil.doubleFormat(dateJson.get("qrCode").get("value").asText()));
            NameDouble data9 = new NameDouble("扫一扫", StringUtil.doubleFormat(dateJson.get("scanning").get("value").asText()));

            tempDatas.add(data1);
            tempDatas.add(data2);
            tempDatas.add(data3);
            tempDatas.add(data4);
            tempDatas.add(data5);
            tempDatas.add(data6);
            tempDatas.add(data7);
            tempDatas.add(data8);
            tempDatas.add(data9);
            SeriesData tempSeriesData = new SeriesData(date,tempDatas,"");
            seriesDatas.add(tempSeriesData);
        }
        return seriesDatas;
    }

    private List<SeriesData> getBarData1(JsonNode data) {
        List<SeriesData> seriesDatas = new ArrayList<>();
        JsonNode jsonNode = data.get("userNatureSources");
        for (JsonNode node : jsonNode) {
            List<NameDouble> tempDatas = new ArrayList<>();

            String date = node.get("date").get("value").asText();
            NameDouble nameDouble1 = new NameDouble("自然流量（其他）",node.get("naturalCount").get("value").asDouble());
            NameDouble nameDouble2 = new NameDouble("威尔仕",node.get("wesCount").get("value").asDouble());
            NameDouble nameDouble3 = new NameDouble("UTC",node.get("utcCount").get("value").asDouble());

            tempDatas.add(nameDouble1);
            tempDatas.add(nameDouble2);
            tempDatas.add(nameDouble3);

//            SeriesData seriesData = new SeriesData(date,tempDatas, DateUtil.getDateLong());
            SeriesData seriesData = new SeriesData(date,tempDatas,"");
            seriesDatas.add(seriesData);
        }
//        return seriesDatas.stream().sorted(Comparator.comparing(SeriesData::getSort)).collect(Collectors.toList());
        return seriesDatas;
    }

    public void table(XSLFShape shape, JsonNode data) {
        TableShape tableShape = (TableShape)shape;
        int numberOfColumns = tableShape.getNumberOfColumns();
        int numberOfRows = tableShape.getNumberOfRows();

        //获取jsonKey
        String rawText = ((XSLFTextParagraph) (tableShape.getCell(1, 0)).getTextParagraphs().get(0)).getTextRuns().get(0).getRawText();
        String jsonKey;
        if (rawText.equals("UTC")){
            jsonKey = "userNatureSources";
        }else if (rawText.equals("一键组队")){
            jsonKey = "userChannelSources";
        }else {
            jsonKey = "page8s";
        }

        //遍历获取每一个单元格
        for (int col =1 ;col < numberOfColumns; col++){
            JsonNode colData = data.get(jsonKey).get(col - 1);
            for (int row = 0; row<numberOfRows; row++ ){
                TableCell cell = tableShape.getCell(row, col);
                if (cell.getTextParagraphs().size() > 0){
                    XSLFTextParagraph cellParagraphs = (XSLFTextParagraph)cell.getTextParagraphs().get(0);
                    if (cellParagraphs.getTextRuns().size()> 0){
                        XSLFTextRun textRun = cellParagraphs.getTextRuns().get(0);
                        textRun.setFontSize(10d);
                        textRun.setText(getCellData(colData, row, jsonKey));
                    }
                }
            }
        }
    }

    private String getCellData(JsonNode colData, int row, String jsonKey){

        try {
            String jsonKey1;
            switch (row){
                case 0:
                    return colData.get("date").get("value").asText();
                case 1:
                    if (jsonKey.equals("userNatureSources")){
                        jsonKey1 = "utcCount";
                        break;
                    } else if (jsonKey.equals("page8s")) {
                        jsonKey1 = "otherApp";
                        break;
                    }else {
                        jsonKey1 = "teamCount";
                        break;
                    }
                case 2:
                    if (jsonKey.equals("userNatureSources")){
                        jsonKey1 = "naturalCount";
                        break;
                    } else if (jsonKey.equals("page8s")) {
                        jsonKey1 = "conversation";
                        break;
                    }else {
                        jsonKey1 = "appletCount";
                        break;
                    }
                case 3:
                    if (jsonKey.equals("userNatureSources")){
                        jsonKey1 = "wesCount";
                        break;
                    } else if (jsonKey.equals("page8s")) {
                        jsonKey1 = "taskUsed";
                        break;
                    }else {
                        jsonKey1 = "king";
                        break;
                    }
                case 4:
                    jsonKey1 = "search";
                    break;
                case 5:
                    jsonKey1 = "taskMyApp";
                    break;
                case 6:
                    jsonKey1 = "pubMenu";
                    break;
                case 7:
                    jsonKey1 = "pubArticle";
                    break;
                case 8:
                    jsonKey1 = "qrCode";
                    break;
                case 9:
                    jsonKey1 = "scanning";
                    break;
                default:
                    jsonKey1 = "";
                    break;
            }
            return StringUtil.decimalFormat(StringUtil.doubleFormat(colData.get(jsonKey1).get("value").asText()));
        }catch (Exception e){
//            logService.setDataLogStatus("ppt-error");
            return " ";
        }
    }
}
